package org.sfgeeq.chapter2.helper;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.sfgeeq.chapter2.util.PropsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

/**
 * 数据库操作助手类
 * Created by  on 2016/8/25.
 */
public class DatabaseHelper {
    private static final Logger log= LoggerFactory.getLogger(DatabaseHelper.class);

    private static final String DRIVER;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;
    static {
        Properties conf= PropsUtil.loadProps("config.properties");
        DRIVER=conf.getProperty("jdbc.driver");
        URL=conf.getProperty("jdbc.url");
        USERNAME=conf.getProperty("jdbc.username");
        PASSWORD=conf.getProperty("jdbc.password");
        try{
            Class.forName(DRIVER);
        }catch (ClassNotFoundException e){
            log.error("can not load jbdc driver(无法加载jdcb)",e);
        }
    }
    /**
     * 获取数据库连接
     */
    public static Connection getConnection(){
        Connection conn=null;
        try{
            conn= DriverManager.getConnection(URL,USERNAME,PASSWORD);
        }catch (SQLException e){
            log.error("获取数据库连接失败",e);
        }
        return conn;
    }

    /**
     * 关闭数据库连接
     */
    public static void closeConnection(Connection conn){
        if(conn !=null){
            try {
                conn.close();
            } catch (SQLException e) {
                log.error("数据库连接关闭失败。",e);
            }
        }
    }


//    ----------------------------使用 DBUtils 工具类来实现查询 --------------------------------------------
private static final QueryRunner QUERY_RUNNER=new QueryRunner();

    /**
     * 查询实体列表
     * @param entityClass
     * @param sql           要查询的SQL
     * @param params        查询的入参
     * @param <T>
     * @return
     */
    public static <T> List<T> queryEntityList(Class<T> entityClass,Connection conn ,String sql,Object... params){
        List<T> entityList;
        try {
            entityList=QUERY_RUNNER.query(conn,sql,new BeanListHandler<T>(entityClass),params);
        } catch (Exception e) {
            log.error("execute query failure(执行查询出错)",e);
            throw new RuntimeException(e);
        }finally {
            closeConnection(conn);
        }
        return entityList;
    }

}
